﻿using System;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

namespace DataAccess
{
    /// <summary>
    /// 数据存储
    /// </summary>
    public class DataWriter
    {
        /// <summary>
        /// 单例模式
        /// </summary>
        private static readonly DataWriter instance = new DataWriter();
        public static DataWriter Instance
        {
            get
            {
                return instance;
            }
        }
        /// <summary>
        /// web程序根目录
        /// </summary>
        private readonly string WebRoot;

        /// <summary>
        /// 数据库连接句柄
        /// </summary>
        private readonly SqlConnection Handle;

        /// <summary>
        /// 构造函数
        /// </summary>
        private DataWriter()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string ip = config.AppSettings.Settings["ip"].Value;
            string name = config.AppSettings.Settings["name"].Value;
            string user = config.AppSettings.Settings["user"].Value;
            string password = config.AppSettings.Settings["password"].Value;
            WebRoot = Environment.GetEnvironmentVariable("BlueGod") + "\\Web";
            Public.WriteLog("WebRoot: " + WebRoot);
            if (!Directory.Exists(WebRoot))
            {
                Directory.CreateDirectory(WebRoot);
            }
            string connectStr = "Data Source=" + ip + ";Initial Catalog=" + name + ";Persist Security Info=True;user ID=" + user + ";password=" + password + ";MultipleActiveResultSets=True";
            Public.WriteLog(connectStr);
            Handle = new SqlConnection(connectStr);
            Handle.Open();
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        public void Replace(string table, string name, string director, string actor, string type, string region, string duration, string firstShowTime,
            string introduction, byte[] posterFileBytes, byte[] screenshootFileBytes, string ftpUrl, string magnetUrl, string source)
        {
            Public.WriteLog("----- DataWriter Save " + table + " Information" + "《" + name + "》" + "-----");
            Public.WriteLog(ftpUrl);
            Public.WriteLog(magnetUrl);

            try
            {
                lock (Handle)
                {
                    string sql = "IF NOT EXISTS (SELECT * FROM " + table + " WHERE name = @name AND source = @source) INSERT INTO " + table;
                    sql += "(name, director, actor, type, region, duration, first_showtime, introduction, poster_file_name, screenshoot_file_name, ftp_url, magnet_url, source, create_time) VALUES ";
                    sql += "(@name, @director, @actor, @type, @region, @duration, @first_showtime, @introduction, @poster_file_name, @screenshoot_file_name, @ftp_url, @magnet_url, @source, @create_time) ";
                    sql += "ELSE UPDATE " + table + " SET ";
                    sql += "director = @director, ";
                    sql += "actor = @actor, ";
                    sql += "type = @type, ";
                    sql += "region = @region, ";
                    sql += "duration = @duration, ";
                    sql += "first_showtime = @first_showtime, ";
                    sql += "introduction = @introduction, ";
                    sql += "poster_file_name = @poster_file_name, ";
                    sql += "screenshoot_file_name = @screenshoot_file_name, ";
                    sql += "ftp_url = @ftp_url, ";
                    sql += "magnet_url = @magnet_url, ";
                    sql += "update_time = @update_time WHERE ";
                    sql += "name = @name AND source = @source";

                    SqlCommand sqlCmd = new SqlCommand(sql, Handle);
                    sqlCmd.Parameters.AddWithValue("name", name);
                    sqlCmd.Parameters.AddWithValue("director", director);
                    sqlCmd.Parameters.AddWithValue("actor", actor);
                    sqlCmd.Parameters.AddWithValue("type", type);
                    sqlCmd.Parameters.AddWithValue("region", region);
                    sqlCmd.Parameters.AddWithValue("duration", duration);
                    sqlCmd.Parameters.AddWithValue("first_showtime", firstShowTime);
                    sqlCmd.Parameters.AddWithValue("introduction", introduction);

                    string imagesFold = WebRoot + "\\images\\" + table + "\\";

                    string posterFileName = "";
                    if (posterFileBytes != null)
                    {
                        posterFileName = source.Replace(":", ".").Replace("/", "") + "." + name + ".poster.jpg";
                        Public.WriteAllBytes(imagesFold, posterFileName, posterFileBytes);
                    }

                    string screenshootFileName = "";
                    if (screenshootFileBytes != null)
                    {
                        screenshootFileName = source.Replace(":", ".").Replace("/", "") + "." + name + ".screenshoot.jpg";
                        Public.WriteAllBytes(imagesFold, screenshootFileName, screenshootFileBytes);
                    }


                    sqlCmd.Parameters.AddWithValue("poster_file_name", posterFileName);
                    sqlCmd.Parameters.AddWithValue("screenshoot_file_name", screenshootFileName);

                    sqlCmd.Parameters.AddWithValue("ftp_url", ftpUrl);
                    sqlCmd.Parameters.AddWithValue("magnet_url", magnetUrl);

                    sqlCmd.Parameters.AddWithValue("source", source);

                    string time = DateTime.Now.ToString("yyy-MM-dd HH:mm:ss");
                    sqlCmd.Parameters.AddWithValue("create_time", time);
                    sqlCmd.Parameters.AddWithValue("update_time", time);

                    int ret = sqlCmd.ExecuteNonQuery();
                    Public.WriteLog("ExecuteNonQuery ret = " + ret.ToString());
                }
            }
            catch (Exception e)
            {
                Public.WriteLog("Save " + table + " Information Exception: " + e.Message);
                throw;
            }
        }
    }
}